<template>
  <div class="wallpaper-admin">
    <!-- 操作栏卡片 -->
    <div class="admin-actions">
      <el-button type="primary" plain @click="handleAdd" class="action-button">
        <el-icon>
          <Plus/>
        </el-icon>
        <span>新增壁纸</span>
      </el-button>
      <el-button type="danger" plain @click="delBatch" class="action-button" :disabled="!data.ids.length">
        <el-icon>
          <Delete/>
        </el-icon>
        <span>批量删除</span>
      </el-button>
    </div>

    <!-- 壁纸列表卡片 -->
    <div class="wallpaper-list">
      <el-table
          stripe
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          class="wallpaper-table"
          empty-text="暂无壁纸数据"
      >
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column prop="index" label="序号" type="index" width="80" align="center"></el-table-column>

        <el-table-column prop="avatar" label="壁纸预览" align="center">
          <template v-slot="scope">
            <div class="wallpaper-preview">
              <el-image
                  :src="scope.row.images"
                  :preview-src-list="[scope.row.images]"
                  preview-teleported
                  fit="cover"
                  class="wallpaper-image"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon>
                      <Picture/>
                    </el-icon>
                  </div>
                </template>
              </el-image>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180" fixed="right" align="center">
          <template v-slot="scope">
            <el-button
                type="primary"
                circle
                :icon="Edit"
                @click="handleEdit(scope.row)"
                class="action-icon"
            ></el-button>
            <el-button
                type="danger"
                circle
                :icon="Delete"
                @click="del(scope.row.id)"
                class="action-icon"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-wrapper" v-if="data.total">
      <el-pagination
          @current-change="load"
          background
          layout="prev, pager, next"
          :page-size="data.pageSize"
          v-model:current-page="data.pageNum"
          :total="data.total"
      />
    </div>

    <!-- 壁纸编辑对话框 -->
    <el-dialog
        :title="data.form.id ? '编辑壁纸' : '新增壁纸'"
        v-model="data.formVisible"
        width="500px"
        destroy-on-close
        class="wallpaper-dialog"
    >
      <el-form ref="form" :model="data.form" label-width="80px" label-position="top">
        <el-form-item prop="images">
          <el-upload
              :action="baseUrl + '/files/upload'"
              :on-success="handleFileUpload"
              list-type="picture-card"
              :file-list="data.form.images ? [{url: data.form.images}] : []"
          >
            <el-icon>
              <Plus/>
            </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false" class="dialog-button">取消</el-button>
          <el-button type="primary" @click="save" class="dialog-button">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {reactive} from "vue";
import request from "@/utils/request.js";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit} from "@element-plus/icons-vue";

const baseUrl = import.meta.env.VITE_BASE_URL;

const data = reactive({
  formVisible: false,
  tableData: [],
  pageNum: 1,
  pageSize: 5,
  total: 0,
  ids: [],
  form: {}
})

const load = () => {
  request.get('/banner/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data?.list || []
      data.total = res.data?.total
    }
  })
}
const handleAdd = () => {
  data.form = {}
  data.formVisible = true
}
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row))
  data.formVisible = true
}
const add = () => {
  request.post('/banner/add', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      load()
    } else {
      ElMessage.error(res.msg)
    }
  })
}

const update = () => {
  request.put('/banner/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功')
      data.formVisible = false
      load()
    }
  })
}

const save = () => {
  data.form.id ? update() : add()
}

const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/banner/delete/' + id).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    console.error(err)
  })
}
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据")
    return
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete("/banner/delete/batch", {data: data.ids}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功')
        load()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }).catch(err => {
    console.error(err)
  })
}
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id)
}

const handleFileUpload = (res) => {
  data.form.images = res.data
}

load()
</script>

<style scoped>
.wallpaper-admin {
  padding: 20px;
  background-color: #f5f7fa;
}

.admin-actions {
  background: #fff;
  padding: 15px 20px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  gap: 10px;
}

.action-button {
  display: flex;
  align-items: center;
  gap: 5px;
}

.wallpaper-list {
  background: #fff;
  padding: 15px;
  margin-bottom: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.wallpaper-table {
  width: 100%;
}

.wallpaper-preview {
  display: flex;
  justify-content: center;
}

.wallpaper-image {
  width: 80px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
}

.image-error {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  background: #f5f5f5;
  color: #999;
}

.action-icon {
  margin: 0 5px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}


.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.dialog-button {
  min-width: 80px;
}
</style>